package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExeptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
        public R<String> handlerSQLConstraintException(SQLIntegrityConstraintViolationException es){
        String message = es.getMessage();
        if (message.contains("Duplicate entry")){
            String[] s = message.split(" ");
            return R.error(s[2]+" 已存在");
        }

        return R.error("数据异常");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        String message = ex.getMessage();
        log.error(message);
        return R.error(message);
    }


}
